﻿using CommunityToolkit.Mvvm.Input;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WPF.Core;
using WPF.Core.Services;

namespace WPF.Zero.ViewModels
{
    public partial class LoginViewModel : DialogViewModel
    {
        private readonly UserService appService;
        private readonly IDialogService dialogService;

        public LoginViewModel(IDialogService dialogService, UserService appService)
        {
            this.appService = appService;
            this.dialogService = dialogService;
        }

        private string userName;
        private string password;

        private int selectedIndex;

        /// <summary> 
        /// 语言切换索引
        /// </summary>
        public int SelectedIndex
        {
            get { return selectedIndex; }

            set
            {
                selectedIndex = value;
                UpdateLanguage();
                RaisePropertyChanged();
            }
        }


        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get { return password; }
            set { password = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 注册
        /// </summary>
        [RelayCommand]
        public async void Register()
        {
            dialogService.ShowDialog("RegisterView");
        }

        /// <summary>
        /// 登录
        /// </summary>
        [RelayCommand]
        public async void Login()
        {
            if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password)) return;

            await SetBusyAsync(async () =>
            {
                var _user = await appService.LoginAsync(UserName, Password);
                if (_user == null)
                {
                    MessageBox.Show("用户名或密码错误!");
                    return;
                }
                await Task.Delay(1000);
                //缓存当前的用户信息
                OnDialogClosed();
            });

        }

        private void UpdateLanguage()
        {
            var language = SelectedIndex == 0 ? "zh-CN" : "en-US";

            var resouce = App.Current.Resources.MergedDictionaries.FirstOrDefault(x => x.Source != null && x.Source.OriginalString.Contains(language));

            if (resouce != null)
            {
                App.Current.Resources.MergedDictionaries.Remove(resouce);
                App.Current.Resources.MergedDictionaries.Add(resouce);
            }
            
        }
    }
}
